#导入session
from flask import current_app, jsonify
from flask import g
from flask import request
from flask import session, render_template
#导入蓝图对象
from info import constants
from info.models import User, Category, CommentLike
from info.utils.commons import login_required
from info.utils.response_code import RET
from . import new_blu
from info.models import News
from info import db
from info.models import Comment


#使用蓝图对象
@new_blu.route('/')
def index():
    #展示用户登录信息
    #1、尝试从redis数据库中获取用户的缓存信息
    #2、判断获取结果是否存在
    #3、通过use_id查询mysql数据库
    #4、判断查询结果
    user_id = session.get('user_id')
    user = None
    if user_id:
        try:
            user = User.query.filter_by(id=user_id).first()
            print(user)
            # user = User.query.get(user_id)
        except Exception as e:
            current_app.logger.error(e)
    #项目首页点击排行
    #1、查询数据，并分页
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(6)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询新闻失败')
    #2、判断查询结果
    if not news_list:
        return jsonify(errno=RET.PARAMERR, errmsg='无新闻数据')
    #3、定义容器，存储查询结果对象转成的字典数据
    news_dict_list = []
    for news in news_list:
        news_dict_list.append(news.to_dict())

    #首页分页数据的加载
    try:
        categories = Category.query.all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询分类数据失败')
    if not categories:
        return jsonify(errno=RET.DATAERR, errmsg='分类数据不存在')
    category_list = []
    for category in categories:
        category_list.append(category.to_dict())

    data = {
        'user_info': user.to_dict() if user else None,
        'news_dict_list':news_dict_list,
        'category_list':category_list
    }
    return render_template('news/index.html', data=data)


@new_blu.route('/news_list')
def get_new_list():
    """
    项目首页新闻列表
    1、获取参数
    2、校验参数，把数据类型转成int
    3、根据cid查询数据库，默认按照新闻的发布时间排序，分页（paginate）
    4、遍历分页后的数据，转成字典
    5、返回数据
    :return:
    """
    cid = request.args.get('cid', '1')
    page = request.args.get('page', '1')
    per_page = request.args.get('per_page', '10')
    try:
        cid, page, per_page = int(cid), int(page), int(per_page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg='参数类型错误')
    filters = []
    if cid > 1:
        filters.append(News.category_id == cid)
    try:
            # 默认按照新闻分类进行过滤，按照新闻发布时间倒序排序，分页每页10条
        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page,constants.HOME_PAGE_MAX_NEWS,False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询数据失败')
    news_list = paginate.items
    total_page = paginate.pages
    current_page = paginate.page
    news_dict_list = []
    for news in news_list:
        news_dict_list.append(news.to_dict())
    data = {
        'news_dict_list':news_dict_list,
        'total_page':total_page,
        'current_page':current_page
    }
    return jsonify(errno=RET.OK, errmsg='OK', data=data)

@new_blu.route('/<int:news_id>')
@login_required
def get_new_detail(news_id):
    """
    新闻详情页面
    1、判断用户的登录状态
    2、获取news_id,查询数据库
    3、判断查询结果
    4、返回新闻的详情数据

    :return:
    """
    user = g.user
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询新闻数据失败')
    if not news:
        return jsonify(errno=RET.DATAERR, errmsg='无新闻数据')
    news.clicks += 1
    try:
        db.session.add(news)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(RET.DBERR, errmsg='保存数据失败')

    data = {
        'user':user.to_dict() if user else None,
        'news':news.to_dict()
    }

    return render_template('news/detail.html', data=data)


@new_blu.route('/news_collect', methods = ['POST'])
@login_required
def news_collect():
    """
    收藏和取消收藏
    1、尝试获取用户的登录信息
    2、获取参数 news——id， action
    3、校验参数的完整性
    4、检查action参数的范围
    5、news-id转成int类型， 查询数据库
    :return:
    """
    user = g.user
    if not user:
        return jsonify(errno=RET.DBERR, errmsg='用户未登录')
    news_id = request.json.get('news_id')
    action = request.json.get('action')
    if not all([news_id, action]):
        print(news_id)
        return jsonify(errno=RET.PARAMERR, errmsg='参数不完整')
    try:
        news_id = int(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR,errmsg='参数格式错误')
    if action not in ['collect','cancel_collect']:
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询数据失败')
    if not news:
        return jsonify(errno=RET.NODATA,errmsg='无新闻数据')
    if action == 'collect':
        if news not in user.collection_news:
            user.collection_news.append(news)
    else:
        user.collection_news.remove(news)
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg='保存数据失败')
        # 返回结果
    return jsonify(errno=RET.OK, errmsg='OK')


@new_blu.route('/news_comment', methods=['POST'])
@login_required
def comment_news():
    """
    评论新闻
    1、判断用户是否登录
    2、获取参数news_id,comment,parent_id
    3、检查参数的完整性
    4、校验news_id，parent_id转成整型
    5、根据news_id查询数据库
    6、实例化评论表对象， 保存评论id，新闻id，新闻内容
    7、提交数据返回结果
    :return:
    """
    user = g.user
    if not user:
        return jsonify(errrno=RET.DBERR, errmsg='用户未登录1')
    news_id = request.json.get('news_id')
    content = request.json.get('content')
    parent_id = request.json.get('parent_id')
    if not all([news_id, content, parent_id]):

        return jsonify(errrno=RET.DBERR, errmsg='参数不完整1')
    try:
        news_id = int(news_id)
        if parent_id:
            parent_id = int(parent_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errrno=RET.DBERR, errmsg='参数类型不正确1')
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errrno=RET.DBERR, errmsg='查询新闻数据失败')
    if not news:
        return jsonify(errrno=RET.DBERR, errmsg='新闻数据不存在')
    comment = Comment()
    comment.news_id = news_id
    comment.user_id = user.id
    comment.content = content
    if parent_id:
        comment.parent_id = parent_id
    try:
        db.session.add(news)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errrno=RET.DBERR, errmsg='保存数据失败1')
    return jsonify(errrno=RET.OK, errmsg='OK', data=comment.to_dict())
    


@new_blu.route('/comment_like', methods=['POST'])
@login_required
def comment_like():
    """
    点赞或取消点赞
    1、获取用户登录状态
    2、获取参数comment_id,action
    3、检查参数的完整性
    4、判断action是否为add，remove
    5、把comment_id转为整型
    6、根据comment_id,查询数据库
    7、判断查询结果
    8、判断行为是点赞还是取消点赞
    9、如果为点赞，点赞次数加1，否则减1
    10、提交数据
    11、返回结果
    :return:
    """
    user = g.user
    if not user:
        return jsonify(errrno=RET.DBERR, errmsg='用户为登录')
    comment_id = request.json.get('comment_id')
    action = request.json.get('action')
    news_id = request.json.get('news_id')
    if not all([comment_id, news_id, action]):
        return jsonify(errrno=RET.DBERR, errmsg='参数不完整2')
    if action not in ['add', 'remove']:
        return jsonify(errrno=RET.DBERR, errmsg='参数范围不正确2')
    try:
        news_id, comment_id = int(news_id), int(comment_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errrno=RET.DBERR, errmsg='参数格式不正确2')
    try:
        comments = Comment.query.get(comment_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errrno=RET.DBERR, errmsg='查询数据失败2')
    if not comments:
        return jsonify(errrno=RET.DBERR, errmsg='评论不存在')

    if action == 'add':
        comment_like_model = CommentLike.query.filter(CommentLike.user_id==user.id, CommentLike.comment_id==comment_id).first()
        # if not comment_like_model:





    pass





@new_blu.route('/followed_user', methods=['POST'])
@login_required
def followed_user():
    """
    1、获取用户信息，判断用户是否登录
    2、获取参数
    3、校验参数的完整性
    4、校验参数是否在关注与取消关注之间
    5、根据他人用户id获取被关注或取消的用户
    6、判断关注还是取消关注
    :return:
    """
    user = g.user
    if not user:
        return jsonify(errrno=RET.DBERR, errmsg='用户未登录3')
    user_id = request.json.get('user_id')
    action = request.json.get('action')
    if not all([user_id, action]):
        return jsonify(errrno=RET.DBERR, errmsg='参数不完整3')

    if action not in ['followed','unfollow']:
        return jsonify(errrno=RET.DBERR, errmsg='参数范围不正确3')

    try:
        other = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errrno=RET.DBERR, errmsg='查询被关注用户失败')
    if not other:
        return jsonify(errrno=RET.DBERR, errmsg='被关注用户不存在')

    if action == 'followed':
        if other not in user.followed:
            user.followed.append(other)
        else:
            return jsonify(errrno=RET.DBERR, errmsg='该用户已经被关注')
    if action == 'unfollow':
        if other in user.followed:
            user.followed.remove(other)
        else:
            return jsonify(errrno=RET.DBERR, errmsg='该用户未关注')
    return jsonify(errrno=RET.OK, errmsg='OK')







#加载项目图标
@new_blu.route('/favicon.ico')
def favicon():
    #静态路径访问的默认实现：send_static_file
    #把静态文件发给浏览器
    return current_app.send_static_file('news/favicon.ico')



















